package com.translate.web.service.impl;

import com.common.util.SnowFlake;
import com.translate.web.constant.RedisConstant;
import com.translate.web.dao.ReceivablesMapper;
import com.translate.entity.Receivables;
import com.translate.web.service.IReceivablesService;
import com.basic.service.impl.BaseServiceImpl;

import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class ReceivablesServiceImpl extends BaseServiceImpl<Receivables> implements IReceivablesService {
	
	private RedisTemplate<String, Receivables> redisTemplate;
	
	public ReceivablesServiceImpl(ReceivablesMapper mapper) {
		super(mapper);
	}

	protected void insertPropteris(Receivables data) {
		long time = System.currentTimeMillis() / 1000;
		data.setCreateTime(time);
		data.setUpdateTime(time);
	}

	protected void updatePropteris(Receivables data) {
		data.setUpdateTime(System.currentTimeMillis() / 1000);
	}

	protected Class<Receivables> getEntityClass() {
		return Receivables.class;
	}
	
	@Override
	public int insert(Receivables data) {

		this.insertPropteris(data);
		
		SnowFlake snowFlake = new SnowFlake(0, 0);
		
		data.setNumber(snowFlake.nextId() + "");

		return this.getBaseMapper().insert(data);
	}

	@Override
	public Receivables getReceivablesToCache(int id) {
		
		String key = RedisConstant.getReceivablesKey(id);
		
		ValueOperations<String, Receivables> valueOperations = this.redisTemplate.opsForValue();
		
		Receivables receivables = valueOperations.get(key);
		
		if (null !=receivables) {
			return receivables;
		}
		
		receivables = this.getBaseMapper().selectByPrimaryKey(id);
		
		if (null == receivables) {
			receivables = new Receivables();
			
			valueOperations.set(key, receivables, 3, TimeUnit.SECONDS);
			
			return receivables;
		}
		
		valueOperations.set(key, receivables, 15, TimeUnit.SECONDS);
		
		return receivables;
	}

	@Autowired
	public void setRedisTemplate(RedisTemplate<String, Receivables> redisTemplate) {
		this.redisTemplate = redisTemplate;
	}

	@Override
	@Transactional
	public int agree(int orderId) {
		
		Receivables receivables = new Receivables();
		
		receivables.setId(orderId);
		
		receivables.setStatus((byte)1);
		
		return this.mapper.updateByPrimaryKeySelective(receivables);
		
	}

	@Override
	@Transactional
	public int reject(int orderId) {
		
		Receivables receivables = new Receivables();
		
		receivables.setId(orderId);
		
		receivables.setStatus((byte)2);
		
		return this.mapper.updateByPrimaryKeySelective(receivables);
		
	}

	@Override
	public boolean editable(int id) {
		
		Receivables receivables = this.selectByPrimaryKey(id);
		
		return 0 == receivables.getStatus().compareTo((byte)2);
		
	}
}